import { ToastIcon } from '@/components/bs-icons/toast'
import { cname } from '@/components/bs-ui/utils'
import { CaretDownIcon } from '@radix-ui/react-icons'
import { useMemo, useState } from 'react'
import { CitationsType } from './types'

export default function RunLog({ data = [] }: { data: CitationsType[] }) {
  const [open, setOpen] = useState(false)

  const [title, detail] = useMemo(() => {
    if (!data.length) {
      return ['', '']
    }

    // 溯源信息中最多包含一种类型
    const type = data[0].type
    const startInfo = type === 'knowledge' ? '已搜索' : '已使用'

    let title = ''
    if (type === 'plugin') {
      title = startInfo + data.map(item => item.title).filter(item => item)
    } else if (type === 'knowledge') {
      title = startInfo + data.map(item => item.knowledge_name).filter(item => item)
    }

    let detail = ''
    try {
      detail = data.map(item => (item.detail?.length ? JSON.stringify(item.detail) : '')).join('\n')
    } catch (error) {
      console.error('data detail解析异常', error)
      detail = '详细信息解析异常'
    }
    return [title, detail]
  }, [data])

  return (
    <>
      {data.length ? (
        <div className="py-1">
          <div className="rounded-sm border">
            <div className="flex cursor-pointer items-center justify-between px-4 py-2" onClick={() => setOpen(!open)}>
              <div className="flex items-center gap-2 text-sm font-bold">
                <ToastIcon type="success" />
                <span>{title}</span>
              </div>
              {!!detail && <CaretDownIcon className={open ? 'rotate-180' : ''} />}
            </div>
            <div
              className={cname(
                'overflow-hidden bg-gray-100 px-4 py-2 text-sm text-gray-500 ',
                !!detail && open ? 'h-auto' : 'h-0 p-0'
              )}
            >
              <p>{detail}</p>
            </div>
          </div>
        </div>
      ) : (
        <></>
      )}
    </>
  )
}
